'use strict';
var module = angular.module('test', []);
module.controller('test.controller', ['$scope', '$http', function($scope, $http) {
    //初始化
    $scope.pobj = {
        items: [],
        count: 0,
        index: 1
    };
    //服务器获取数据
    $scope.$watch('pobj.index', function(nValue, oValue){
        console.log($scope.pobj.index);
        if ($scope.pobj.index > 0) {
            $http.get('Service.js').then(function(res) {
                $scope.pobj.items = res.data.records.slice(($scope.pobj.index - 1) * 10, ($scope.pobj.index - 1) * 10 + 10);
                $scope.pobj.count = res.data.records.length;
            });
        }
    }, true);
}])
module.directive('bootPager', [function() {
    return {
        scope: {
            pobj: '='
        },
        restrict: 'EA',
        templateUrl: 'Pager.html',

        link: function($scope, iElm, iAttrs, controller) {
            $scope.selectPage = function(page) {
                //不能小于1大于最大
                if (page < 1 || page > $scope.pages) return;
                //显示9页（第五页开始向后加载）
                if (page > 5) {
                    var newpageList = [];
                    for (var i = (page - 5); i < ((page + 4) > $scope.pages ? $scope.pages : (page + 4)); i++) {
                        newpageList.push(i + 1);
                    }
                    $scope.pageList = newpageList;
                }
                else {
                    var newpageList = [];
                    for (var i = 0; i < $scope.newPages; i++) {
                        newpageList.push(i + 1);
                    }
                    $scope.pageList = newpageList;
                }
                $scope.pobj.index = page;
                $scope.isActivePage(page);
            };

            //设置当前选中页样式
            $scope.isActivePage = function(page) {
                return $scope.pobj.index == page;
            };
            //上一页
            $scope.Previous = function() {
                $scope.selectPage($scope.pobj.index - 1);
            }
                //下一页
            $scope.Next = function() {
                $scope.selectPage($scope.pobj.index + 1);
            };
        },
        controller: ['$scope', function($scope) {
            //一般监控进入两次（初始化一次，count一般变化一次）
            $scope.$watch('pobj.count', function(newValue, oldValue){
                if ($scope.pobj.index == 1 && $scope.pobj.items && $scope.pobj.items.length > 0) {
                    $scope.pageSize = 10;
                    //分页数
                    $scope.pages = Math.ceil($scope.pobj.count / $scope.pageSize);
                    $scope.newPages = $scope.pages > 9 ? 9 : $scope.pages;
                    $scope.pageList = [];
                    //分页页码数组
                    for (var i = 0; i < $scope.newPages; i++) {
                        $scope.pageList.push(i + 1);
                    }
                }
            }, true);
        }]
    };
}]);
